<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
  </head>
  <body>
    <div id="app"   >
         <p>
      Ask a yes/no question:
      <input v-model="question" :disabled="loading" />
    </p>
    <p>{{ answer }}</p>
    <!-- 插入一张图片 -->
    <img v-if="image" :src="image" alt="Answer" />


    </div>
   
  </body>
  <script>
    const { createApp } = Vue
    const app ={
    data() {
        return {
          question: "",
          answer: "Questions usually contain a question mark. ;-)",
          loading: false,
          image: "",

        };
      },
      watch: {
        // 每当 question 改变时，这个函数就会执行
        question(newQuestion, oldQuestion) {
            this.image = '';

          if (newQuestion.includes("?")) {
            this.getAnswer();
          }
        },
      },
      methods: {
        async getAnswer() {
          this.loading = true;
          this.answer = "Thinking...";
          try {
            const res = await fetch("https://yesno.wtf/api");
            this.answers = (await res.json());
            this.answer =this.answers.answer
            this.image = this.answers.image;

          } catch (error) {
            this.answer = "Error! Could not reach the API. " + error;
          } finally {
            this.loading = false;
          }
        },
      },
  }
  createApp(app).mount('#app')
  </script>
</html>
